<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends BaseController {
    /**
     * 主页面
     * 初始化并判断应显示页面
     */
    public function index(){
        header("Content-type: text/html; charset=utf-8");
        $openid = $this->getOpenid();
        $signPackage = $this->getSignPackage();
        $ajaxSign = $this->sign($openid);
        $this->assign('openid',$openid);
        $this->assign('sign',$ajaxSign);
        $this->assign('signPackage',$signPackage);

        //$infoPackage = array(
        //    'imgUrl' => 'Public/Yimiao/images/peach.png',
        //    'link' => U('', '', '', true),
        //    'title' => 'title',
        //    'desc' => 'desc',
        //);
        //$this->assign('infoPackage',$infoPackage);
        
        $sleepingModel  = D('Sleeping');
        $sleepingId = I('get.sid');
        $logModel = D('Log');
        $logModel->addLog($openid, $sleepingId);
        if($sleepingId){
            $info = $sleepingModel->getIdSleeping($sleepingId);
            if(!empty($info) && $info['openid']!=$openid){
                return $this->showGuess($info);
            }
        }
        $info = $sleepingModel->getMySleeping($openid);
        if(!empty($info)){
            if($info['guessnum']>=C('NEED_NUM')){
                return $this->showPrize($info);
            }
        }
        return $this->showIndex($info);
    }
    
    /**
     * 显示猜睡姿页面
     */
    private function showGuess($info)
    {
        $infoPackage = array(
            'imgUrl' => C('URL_PREFIX').'images/share.jpg',
            'link' => U('', '', '', true),
            'title' => '我在参加京东睡眠节猜睡姿赢礼包，快来帮我猜！',
            'desc' => '3.21“京东国际睡眠节”，猜睡姿赢睡眠大礼包，十万份奖品先到先得，每人限领一份！',
        );
        $this->assign('infoPackage',$infoPackage);
        $newInfo['guessnum'] = $info['guessnum'];
        $this->assign('info',$newInfo);
        $this->display('indexf1');
        return;
    }

    /**
     * 显示首页面
     */
    private function showIndex($info)
    {
        $infoPackage = array(
            'imgUrl' => C('URL_PREFIX').'images/share.jpg',
            'link' => U('', '', '', true),
            'title' => '我在参加京东睡眠节猜睡姿赢礼包，快来帮我猜！',
            'desc' => '3.21“京东国际睡眠节”，猜睡姿赢睡眠大礼包，十万份奖品先到先得，每人限领一份！',
        );
        $this->assign('infoPackage',$infoPackage);
        if(empty($info))
            $info = array(
                'guessnum' => 0,
            ); 
        $this->assign('info',$info);
        $this->display('index');
        return;
    }

    /**
     * 显示我的睡姿页面
     */
    private function showPrize($info)
    {
        $infoPackage = array(
            'imgUrl' => C('URL_PREFIX').'images/share.jpg',
            'link' => U('', '', '', true),
            'title' => '我在参加京东睡眠节猜睡姿赢礼包，快来帮我猜！',
            'desc' => '3.21“京东国际睡眠节”，猜睡姿赢睡眠大礼包，十万份奖品先到先得，每人限领一份！',
        );
        $this->assign('infoPackage',$infoPackage);
        $this->assign('info',$info);
        $this->display('index2');
        return;
    }

    private function getLuckyList(){
        $list = S('LuckyUserInfoList');
        if(!empty($list))
            return $list;
        $userInfoModel = D('UserInfo');
        $list = $userInfoModel->getUserInfoList(20);
        $prizeModel = D('Prize');
        $sleepingModel = D('Sleeping');
        foreach($list as $key=>$item){
            $where = array('id'=>$item['sleeping_id']);
            $info = $sleepingModel->field('prize_id')->where($where)->find();
            $prize = $prizeModel->getIdPrizeName($info['prize_id']);
            $list[$key]['prize'] = $prize;
        }
        S('LuckyUserInfoList', $list, array('expire'=>15));
        return $list;
    }

    /**
     * 获得及校验ajax签名
     *
     */
    private function sign($openid, $sign=null)
    {
        if($sign===null){
            $sign = md5($openid.C('AJAX_TOKEN'));
            return $sign;
        }
        if($sign!=md5($openid.C('AJAX_TOKEN'))){
            return false;
        }
        return true;
    }

    public function addSleeping()
    {
        $openid     = I('get.openid');
        $sign       = I('get.sign');
        if(!$this->sign($openid, $sign)){
            return false;
        }
        $sleepingType       = I('get.val');
        $sleepingModel  = D('Sleeping');
        $info = $sleepingModel->getMySleeping($openid);
        if(!empty($info)){
            $result['err'] = 2;
            $result['id'] = $info['id'];
            echo json_encode($result);
            return false;
        }
        $id = $sleepingModel->addSleeping($sleepingType, $openid);
        if(!$id){
            $result['err'] = 1;
            echo json_encode($result);
            return false;
        }
        $result['err'] = 0;
        $result['id'] = $id;
        echo json_encode($result);
    }
    
    public function addGuess()
    {
        $openid     = I('get.openid');
        $sign       = I('get.sign');
        if(!$this->sign($openid, $sign)){
            return false;
        }
        $sleepingType  = I('get.val');
        $sleepingId    = I('get.sid');
        $guessModel  = D('Guess');
        $guess = $guessModel->getMyGuess($sleepingId,$openid);
        if(!empty($guess)){
            $result['err'] = 2;
            echo json_encode($result);
            return false;
        }
        $sleepingModel  = D('Sleeping');
        $info = $sleepingModel->getIdSleeping($sleepingId);
        $right = 0;
        if($info['sleeping_type']==$sleepingType){
            $right = 1;
        }
        $id = $guessModel->addGuess($sleepingId, $sleepingType, $right, $openid);
        $sleepingModel->guessPlus($sleepingId, $right);
        $result = array(
            'err' => 0,
            'id'  => $info['sleeping_type'],
            'right'  => $right,
        );
        echo json_encode($result);
    }

    /**
     * @param get openid
     * @param get sign
     * @return err
     * @return prizeId
     */
    public function addLucky()
    {
        $openid     = I('get.openid');
        $sign       = I('get.sign');
        if(!$this->sign($openid, $sign)){
            return false;
        }
        $sleepingModel  = D('Sleeping');
        $info = $sleepingModel->getMySleeping($openid);
        //如果没有礼盒记录，则返回错误
        if(empty($info)){
            $result['err'] = 2;//没找到记录
            echo json_encode($result);
            return false;
        }
        //如果帮拆人数不到15人，则不允许打开礼盒
        if($info['guessnum']<C('NEED_NUM')){
            $result['err'] = 1;//还不能打开礼盒
            echo json_encode($result);
            return false;
        }
        //如果还未领取过奖品，则领奖
        if($info['prize_time']==0){
            $prizeModel = D('Prize');
            $prize  = $prizeModel->getPrize();
            $sleepingModel->addPrize($prize['id'], $info['id']);
            $result = array(
                'err' => 0,
                'prize'=>$prize['id']
            );
            echo json_encode($result);
            return true;
        }
        //如果中的是优惠券，则返回跳转
        if(empty($info['prize_id'])){
            $result = array(
                'err' => 0,
                'prize'=>$info['prize_id']
            );
            echo json_encode($result);
            return true;
        }
        $userInfoModel = D('UserInfo');
        //是否有用户信息
        $userInfo = $userInfoModel->hasSidUserInfo($info['id']);
        if(!empty($userInfo)){
            $userInfo['address'] = msubstr($userInfo['address'], 0, 10, "utf-8", true);
            $result = array(
                'err' => 3,
                'prize'=>$info['prize_id'],
                'userinfo'=>$userInfo,
            );
            echo json_encode($result);
            return false;
        }
        //如果还没有用户信息，则返回表单
        $result = array(
            'err' => 0,
            'prize'=>$info['prize_id'],
        );
        echo json_encode($result);
        return true;
    }
    
    /**
     * @param get openid
     * @param get sign
     * @param post form
     * @return err
     * @return prizeId
     */
    public function addUserInfo()
    {
        $openid     = I('get.openid');
        $sign       = I('get.sign');
        if(!$this->sign($openid, $sign)){
            return false;
        }
        $sleepingModel  = D('Sleeping');
        $info = $sleepingModel->getMySleeping($openid);
        if(!$info['prize_id']){
            $result['err'] = 1;//还没有中奖呢
            echo json_encode($result);
            return false;
        }
        $form['name'] = I('post.name');
        $form['address'] = I('post.address');
        $form['phone'] = I('post.phone');
        if(empty($form['name']) ||
            empty($form['address']) ||
            empty($form['phone'])){
            $result['err'] = 2;//表单中有空值
            $result['form'] = $form;//表单中有空值
            echo json_encode($result);
            return false;
        }
        $userInfoModel = D('UserInfo');
        $hasUserInfo = $userInfoModel->hasSidUserInfo($info['id']);
        if(!empty($hasUserInfo)){
            $result['err'] = 3;//已有用户数据
            echo json_encode($result);
            return false;
        }
        $id = $userInfoModel->addUserInfo($info['id'], $form);
        $result = array(
            'err' => 0,
            'id'  => $id,
        );
        echo json_encode($result);
    }
}
